package com.qfedu.interceptor;

import com.qfedu.common.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class TimeoutInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //我们使用的是基于注解开发的控制器，这些控制器中的处理请求的方法都是属于HandlerMethod
        //因此，需要在这里先判断我们的处理器类型是否是HandlerMethod，如果不是，直接放行即可
        if(handler instanceof HandlerMethod){
            HttpSession session = request.getSession();
            Object username = session.getAttribute("username");
            //在session中没有找到username属性，说明session已经过期
            if(username == null){
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                PrintWriter writer = response.getWriter();
                String json = JSONObject.toJSONString(R.error(HttpStatus.UNAUTHORIZED.value(), "登陆超时"));
                writer.write(json);
                writer.flush();
                writer.close();
                return false;
            }
            return true;
        }
        return true;
    }
}
